package com.infore.airsupervise.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationListener;
import com.beardedhen.androidbootstrap.AwesomeTextView;
import com.infore.airsupervise.R;
import com.infore.airsupervise.app.Constants;
import com.infore.airsupervise.app.MsgConst;
import com.infore.airsupervise.bean.BaseBean;
import com.infore.airsupervise.biz.impl.EventBizImpl;
import com.infore.airsupervise.http.OnServerResponseListener;
import com.infore.airsupervise.ui.fragment.SelectPhotoFragment;
import com.infore.airsupervise.utils.DialogUtil;
import com.infore.airsupervise.utils.ImageUtil;
import com.infore.airsupervise.utils.LocationUtil;
import com.infore.airsupervise.utils.ToastUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;

/**
 * Created by Administrator on 2017/8/22.
 */

public class SubmitHandlerEventActivity extends BaseActivity implements AMapLocationListener {

    @BindView(R.id.titlebar_left_menu)
    AwesomeTextView titlebarLeftMenu;
    @BindView(R.id.titlebar_title)
    TextView titlebarTitle;
    @BindView(R.id.titlebar_right_menu)
    AwesomeTextView titlebarRightMenu;


    @BindView(R.id.event_local_text)
    TextView mEventLocal;
    @BindView(R.id.rest_Location)
    TextView mRestLocation;
    @BindView(R.id.submit_event_name)
    TextView mEventName;
    @BindView(R.id.submit_station_name)
    TextView mStationName;
    @BindView(R.id.submit_eventhappen_time)
    TextView mEventhappenTime;
    @BindView(R.id.submit_task_person)
    TextView mTaskHandlerPerson;
    @BindView(R.id.submit_event_textdesc)
    EditText mEventTextdesc;
    @BindView(R.id.event_image_container)
    FrameLayout mSelectImage;
    @BindView(R.id.submit_event_data)
    Button mSubmitEventData;
    @BindView(R.id.rest_event_data)
    Button mRestEventData;

    private AMapLocationClient locationClient;
    private AMapLocation userLocation;              // 保存位置对象
    private SelectPhotoFragment selectPhotoFrag;
    private EventBizImpl eventBiz;
    private String eventid;
    private SweetAlertDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_submithandler_event);
        ButterKnife.bind(this);
        // 获取用户位置
        getUserLocation();
        eventBiz = new EventBizImpl();
        Intent intent = getIntent();
        String eventtitle = intent.getStringExtra("eventtitle");
        String eventstation = intent.getStringExtra("eventstation");
        String eventtime = intent.getStringExtra("eventtime");
        String eventperson = intent.getStringExtra("eventperson");
        eventid = intent.getStringExtra("eventid");
        mEventName.setText(eventtitle);
        mStationName.setText(eventstation);
        mEventhappenTime.setText(eventtime);
        mTaskHandlerPerson.setText(eventperson);
        initView();
    }

    private void initView() {

        titlebarTitle.setText("提交处理记录");
        titlebarRightMenu.setVisibility(View.INVISIBLE);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        ViewGroup.LayoutParams lp = mSelectImage.getLayoutParams();    // 获取容器高度
        selectPhotoFrag = new SelectPhotoFragment(5, lp.height);    // 设置可选数、宽度
        transaction.replace(R.id.event_image_container, selectPhotoFrag);
        transaction.commit();

    }

    /**
     * 获取用户位置
     */
    private void getUserLocation() {
        locationClient = new AMapLocationClient(getApplicationContext());
        locationClient.setLocationListener(this);
        locationClient.setLocationOption(LocationUtil.getInstance().getOnceOption());
        locationClient.startLocation();
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        locationClient.stopLocation();
        userLocation = aMapLocation;
        mEventLocal.setText("正在获取位置信息...");
        //addressRefresh.setVisibility(View.VISIBLE);

        if (aMapLocation.getErrorCode() != 0) {
            String[] eInfo = aMapLocation.getErrorInfo().split(" ");
            mEventLocal.setText(eInfo[0]);
            return;
        }

        // 成功则显示位置信息
        mEventLocal.setText(aMapLocation.getAddress());
    }


    @OnClick({R.id.rest_Location, R.id.submit_event_data, R.id.rest_event_data})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rest_Location:
                mEventLocal.setText("正在获取位置信息...");
                locationClient.startLocation();
                break;
            case R.id.submit_event_data:

                commitEventData();

                break;
            case R.id.rest_event_data:
                mEventTextdesc.setText("");
                if(selectPhotoFrag != null){
                    selectPhotoFrag.resetPhotos();
                }
                break;
        }
    }

    /**
     * 提事件记录
     */
    private void commitEventData() {
        // 定位判断
        if (userLocation == null || userLocation.getErrorCode() != 0) {
            ToastUtil.showLong(ctx, "缺少位置信息");
            return;
        }

        // 内容非空判断

        if(TextUtils.isEmpty(mEventName.getText().toString().trim()) ||
                TextUtils.isEmpty(mStationName.getText().toString().trim()) ||
                TextUtils.isEmpty(mEventhappenTime.getText().toString().trim())||
                TextUtils.isEmpty(mTaskHandlerPerson.getText().toString().trim())||
                TextUtils.isEmpty(mEventTextdesc.getText().toString().trim())||
                TextUtils.isEmpty(eventid.trim()) ||
                TextUtils.isEmpty(mEventLocal.getText().toString().trim())){
            ToastUtil.showLong(ctx, "请把信息填写完整");
            return;
        }

        dialog = new SweetAlertDialog(this, SweetAlertDialog.PROGRESS_TYPE)
                .setTitleText(MsgConst.HARD_LOADING)
                .setContentText(MsgConst.PLEASE_WAITING);
        dialog.setCancelable(false);
        dialog.show();

        // 图片集合
        List<String> files = ImageUtil.getInstance().compressOnUpload(selectPhotoFrag.getSelectedPhotos());


        Map<String, Object> param = new HashMap<>();
        param.put("recordId", eventid);
        param.put("handleDescrib", mEventTextdesc.getText());
        param.put("lat", userLocation.getLatitude());
        param.put("lnt", userLocation.getLongitude());
        param.put("address", mEventLocal.getText());


        // 发起请求
        eventBiz.submitEventData(param, files, new OnServerResponseListener<BaseBean>() {
            @Override
            public void onSucceed(BaseBean result, String desc) {
                result.getStatus();
                result.getMessage();
                if (result.getStatus() == 1) {
                    Log.d(" result.getStatus()", result.getStatus() + "---" + result.getMessage());
                    dialog.setTitleText(MsgConst.OPERATION_SUCCESS)
                            .setContentText(desc)
                            .setConfirmText(MsgConst.I_SEE)
                            .changeAlertType(SweetAlertDialog.SUCCESS_TYPE);
                    dialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            setResult(RESULT_OK);//提交成功  返回列表界面是自动刷新
                            finish();
                            dialog.dismiss();
                        }
                    });
                }

            }

            @Override
            public void onFailed(int errorCode, String title, String desc) {
                dialog.setTitleText(MsgConst.OPERATION_FAILED)
                        .setContentText(desc)
                        .setConfirmText(MsgConst.I_SEE)
                        .changeAlertType(SweetAlertDialog.WARNING_TYPE);
            }
        });
    }

    /**
     * 返回上个界面
     */
    @OnClick(R.id.titlebar_left_menu)
    void leftMenuClick() {
        finish();
    }
}
